package agh.tk.markuptranslation.gui;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class OpenAction extends AbstractAction {
	JFrame parent;
	
	public OpenAction(JFrame frame) {
		this.parent = frame;
		putValue(NAME, "Open");
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		//System.out.println("tu open");
		File chosenFile = null;
		JFileChooser fileChooser = Main.fc;
		int returnVal = fileChooser.showOpenDialog(parent);
		if(returnVal == JFileChooser.APPROVE_OPTION) {
			chosenFile = fileChooser.getSelectedFile();
			//System.out.println(chosenFile.getAbsolutePath());
		}
		if(chosenFile == null)
			return;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(chosenFile));
			String newline;
			StringBuilder result = new StringBuilder();
			while((newline = br.readLine())!=null) {
				result.append(newline);
				result.append("\n");
			}
			Main.setFile(chosenFile);
			Main.setText(result.toString());
			
			
		} catch(Exception ex) {
			ex.printStackTrace(System.err);
		} finally {
			try{
				br.close();
			} catch(Exception ex) { }
		}
		
	}
}
